package com.sky.service.user.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.merchant.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MerchantMapper merchantMapper;
    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public Result<UserLoginVO> login(UserLoginDTO userLoginDTO) {

        //1.调用微信接口换取openid
        String openId = getOpenId(userLoginDTO.getCode());
        if (StringUtils.isEmpty(openId)) {
            throw new UserNotLoginException("微信登录失败");
        }

        //根据openid查询用户信息，如果查不到，说明是新用户，保存入库
        User user = userMapper.selectByOpenId(openId);
        if(user==null){
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(user);
        }


        //如果查询到，根据id生成token，返回给前端
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        //查询商家信息
        Merchant merchant = merchantMapper.getShopById(1L);

        //计算配送费
        String merchantLocation = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal delivoryCost = MapUtils.getDelivoryCost(merchantLocation, userLoginDTO.getLocation());

        //构建返回值
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .openid(openId)
                .token(token)
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .shopId(1L)
                .shopAddress(merchant.getShopAddress())
                .id(user.getId())
                .deliveryFee(delivoryCost)
                .build();

        return Result.success(userLoginVO);
    }

    //获取openid
    private String getOpenId(String code) {

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");

        String resJson = HttpClientUtil.doGet(WX_LOGIN_URL, paramMap);

        //解析
        Map map = JSON.parseObject(resJson, Map.class);

        return map.get("openid").toString();
    }
}
